/*
 * compare_display.c
 *
 * Created: 11/21/2011 10:24:47 PM
 *  Author: Thuy Duong
 */ 

#include <stdio.h>
#include <avr/io.h>
#include <util/delay.h>

/*
 * 	- LED connected to PORTB.2
 * 	- Switch connected to PORTD.2
 */

#ifndef F_CPU
#define F_CPU 16000000UL /* or whatever may be your frequency*/
#endif
#include <avr/io.h>
#include <util/delay.h>  
/* BCD for displaying number to 7 segment LED*/
char num[]={0xC0,0xF9,0xA4,0xB0,0x99,0x92,0x82,0xF8,0x80,0x90};
int led1,led2,led3;
float k, a, b, c;
/* a,b,c is received signal from sensor after ADC
   k is the value for display
   led1 is displayed in LED1
   led2 is displayed in LED2
   led3 is displayed in LED3*/

void led7seg(float k) 
{    led1 = k%10;   
	 led2 = k%100-k%10;
	 led2 = k/100;
     DDRB =0xFF; // Port B is set as output
	 DDRC =0x07; // pin 0th, 1st and 2nd are set as output
	 PORTC =0x01; // Turn on the LED1
	 PORTB = num[led1];// Display value led1 on LED1
	 _delay_ms(10);
	 PORTC =0x02; // Turn on the LED2
	 PORTB = num[led2];// Display value led2 on LED2
	 _delay_ms(10);
	  PORTC =0x04; // Turn on the LED3
	 PORTB = num[led3];// Display value led3 on LED3
	 _delay_ms(10);
}

int calculate(int t) 
{
	 int d = 10;
     d = 340.29*t/2 ;/* (speed of sound(340.29m/s))*(time given)/2 = (distance(m))*/
     return d ;
}

int main(void)
{   
	while(1)
    {
		float distance=10;
		distance = calculate(a);
		/* display value of the first sensor, then compare 
		the second sensor value with it, if 2nd is smaller,
		then display value of 2nd. 3th is the same. */
		led7seg(distance);
		_delay_ms(100);
		if (b<a)
		{
			distance = calculate(b);
			led7seg(distance);
			_delay_ms(100);
		} 
		if ((c<a) && (c<b))
		{
			distance = calculate(c);
			led7seg(distance);
			_delay_ms(100);
		}
	 
    } 
}